import keyboard
import win32api
import win32con
import win32gui
# import pynput.keyboard as pk
from pynput.mouse import Listener, Button
import time
import threading

# 句柄列表
hwnd_list = []

stop_event = threading.Event()


# 获取缩放后的鼠标位置
def get_mouse_pos():
    point = win32gui.GetCursorPos()
    return point


# 监听Enter键加入句柄列表
def on_enter_key():
    point = get_mouse_pos()
    hwnd = win32gui.WindowFromPoint(point)
    if hwnd not in hwnd_list:
        hwnd_list.append(hwnd)
        print(f"句柄添加成功: {hwnd}, {hwnd_list}")
    else:
        print(f"句柄已存在: {hwnd}")


window_width = 500
window_height = 400
window_gap = 10


# 监听shift+space通过句柄排序窗口
def sort_window():
    # 获取屏幕大小，计算一行可以放多少个
    # screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    # screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
    # # 已知窗口大小为500*400 间隔为10 计算行和列
    # row = screen_width // 510
    # col = screen_height // 410
    for i, hwnd in enumerate(hwnd_list):
        win32gui.MoveWindow(hwnd, i * (window_width + window_gap), 0, window_width, window_height, True)

    print(f"排序完成: {hwnd_list}")


# 判断当前鼠标是否在窗口内
def is_in_window(hwnd, point):
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    return left <= point[0] <= right and top <= point[1] <= bottom


# 根据鼠标坐标执行其他窗口点击操作
def click_other_window(event, point):
    copy_hwnd_list = hwnd_list[1:]
    for index, hwnd in enumerate(copy_hwnd_list):
        time.sleep(0.5)
        doClick(hwnd, event, point[0], point[1])
        print("点击完成")


def doClick(hwnd, event, cx, cy):  # 第四种，可后台
    # 根据坐标获取句柄
    long_position = win32api.MAKELONG(cx, cy)  # 模拟鼠标指针 传送到指定坐标
    if event in [win32con.WM_LBUTTONDOWN, win32con.WM_LBUTTONUP]:
        win32gui.PostMessage(hwnd, event, win32con.MK_LBUTTON, long_position)
    elif event in [win32con.WM_RBUTTONDOWN, win32con.WM_RBUTTONUP]:
        win32gui.PostMessage(hwnd, event, win32con.MK_RBUTTON, long_position)
    # win32gui.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, long_position)  # 模拟鼠标按下
    # win32gui.PostMessage(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, long_position)  # 模拟鼠标弹起


keyboard.add_hotkey('shift+space', sort_window)
keyboard.add_hotkey('space', on_enter_key)


# 定义鼠标事件处理函数
def on_click(x, y, button, pressed):
    print(f"鼠标事件: {x}, {y}, {button}, {pressed}")
    if stop_event.is_set():
        raise Exception("停止监听")

    if len(hwnd_list) <= 1:
        return
    
    if not is_in_window(hwnd_list[0], (x, y)):
        return
    
    if button == Button.right and pressed:
        click_other_window(event=win32con.WM_RBUTTONDOWN, point=(x, y))
    elif button == Button.right and not pressed:
        click_other_window(event=win32con.WM_RBUTTONUP, point=(x, y))
    elif button == Button.left and pressed:
        click_other_window(event=win32con.WM_LBUTTONDOWN, point=(x, y))
    elif button == Button.left and not pressed:
        click_other_window(event=win32con.WM_LBUTTONUP, point=(x, y))

    # # 检查是否是鼠标左键，并且是按下事件
    # if button == Button.left and pressed:
    #     pass
    # # 检查是否是鼠标左键，并且是弹起事件
    # elif button == Button.left and not pressed:
    #     if len(hwnd_list) > 1:
    #         if is_in_window(hwnd_list[0], (x, y)):
    #             print("鼠标在窗口内")
    #             click_other_window((x, y))
    #             # new_job = threading.Thread(target=click_other_window, args=((x, y),))
    #             # new_job.daemon = True
    #             # new_job.start()
    #         else:
    #             print("鼠标不在窗口内")


def close_main():
    stop_event.set()


keyboard.add_hotkey('shift+esc', close_main)  # 等待按下ESC键退出

def on_move(x, y):
    print(f"鼠标移动: {x}, {y}")

def on_scroll(x, y, dx, dy):
    print(f"鼠标滚动: {x}, {y}, {dx}, {dy}")

def click_event():
    # 创建鼠标监听器
    with Listener(on_click=on_click, on_move=on_move, on_scroll=on_scroll) as listener:
        listener.join()


click_event()

keyboard.wait('esc')
